<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="课程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入课程名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="授课方式" prop="lessonType">
        <el-select
          v-model="queryParams.lessonType"
          placeholder="请选择授课方式"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in edu_teaching_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择课程状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['registrar:course:add']"
          >新增课程</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDeleteList"
          v-hasPermi="['registrar:course:remove']"
          >批量删除</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="courseList"
      border
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" width="55" align="center">
        <template #default="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="课程名称"
        align="center"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="授课方式"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <dict-tag
            :options="edu_teaching_mode"
            :value="scope.row.lessonType"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="收费方式"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template #default> {{ "按课时" }} </template>
      </el-table-column> -->
      <el-table-column
        label="实报价"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <div v-for="price in scope.row.tCoursePriceList" :key="price.id">
            {{
              price.name +
              "(" +
              price.discountedPrice +
              "元" +
              (price.num + price.freeClassHours === 1
                ? "/"
                : price.num + price.freeClassHours) +
              "课时" +
              ")"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="课程状态" align="center" prop="state">
        <template #default="scope">
          <!-- <dict-tag
            class="state-box"
            :options="sys_normal_disable"
            :value="scope.row.state"
            @click="changeState(scope.row)"
          /> -->
          <!--         @change="changeState(scope.row)" -->
          <el-switch
            :disabled="
              !hasPermission(['registrar:course:edit']) ||
              scope.row.openClass === '0'
            "
            v-model="scope.row.state"
            inline-prompt
            size="large"
            active-value="0"
            inactive-value="1"
            active-text="正常"
            inactive-text="停用"
            @change="changeState(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleView(scope.row)"
            v-if="scope.row.openClass === '0'"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['registrar:course:edit']"
            v-if="scope.row.openClass !== '0'"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['registrar:course:remove']"
            v-if="scope.row.openClass !== '0'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer
      v-model="open"
      :title="title"
      :with-header="true"
      size="90%"
      class="course-drawer"
      :close-on-click-modal="false"
      :before-close="closeW"
      :destroy-on-close="true"
    >
      <div class="content">
        <el-form
          ref="dictRef"
          :model="form"
          label-width="auto"
          :disabled="openDisabled"
        >
          <el-form-item
            label="课程名称"
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入课程名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="form.name"
              placeholder="请输入课程名称"
              style="width: 320px"
            />
          </el-form-item>
          <el-form-item label="授课方式" prop="lessonType">
            <el-radio-group v-model="form.lessonType">
              <el-radio
                v-for="dict in edu_teaching_mode"
                :key="dict.value"
                :value="dict.value"
                >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="课表颜色" prop="colour" v-show="false">
            <JnColorPicker v-model="form.colour" />
          </el-form-item>
          <el-form-item label="按课时收费" prop="payType" v-show="false">
            <el-switch
              v-model="form.payType"
              disabled
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>

          <el-form-item
            label="请假是否扣课时"
            prop="askLeavePunish"
            v-show="false"
          >
            <el-radio-group v-model="form.askLeavePunish" disabled>
              <el-radio :value="true">扣</el-radio>
              <el-radio :value="false">不扣</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="未到是否扣课时"
            prop="noShowPunish"
            v-show="false"
          >
            <el-radio-group v-model="form.noShowPunish" disabled>
              <el-radio :value="true">扣</el-radio>
              <el-radio :value="false">不扣</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="description">
            <el-input
              type="textarea"
              v-model="form.description"
              placeholder="请输入内容"
              style="width: 500px"
            />
          </el-form-item>

          <el-card shadow="never">
            <template #header>
              <div style="display: flex; justify-content: space-between">
                <!-- <el-form-item label="按课时收费" prop="payType">
                  <el-switch
                    v-model="form.payType"
                    disabled
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item> -->
                报价单
                <el-button @click="onAddItem"> 添加 </el-button>
              </div>
            </template>
            <el-alert
              title="【温馨提示】报价单至少有一条数据；报价单里课时、总价和折后价均需要大于0"
              type="warning"
              :closable="false"
            />
            <el-table
              class="quotation"
              :data="form.tCoursePriceList"
              style="width: 100%"
              max-height="250"
            >
              <el-table-column
                width="100"
                align="center"
                label="序号"
                prop="index"
              >
                <template #default="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="名称" width="300">
                <template #default="scope">
                  <el-form-item
                    :prop="`tCoursePriceList.${scope.$index}.name`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-input v-model="scope.row.name"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="num" label="课时(节)" width="120">
                <template #default="scope">
                  <el-form-item
                    :prop="`tCoursePriceList.${scope.$index}.num`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入课时数',
                        trigger: 'blur',
                      },
                      { validator: validatenum, trigger: 'blur' },
                    ]"
                  >
                    <el-input
                      v-model="scope.row.num"
                      @change="changeData(scope.row, $event)"
                      @input="
                        (value) =>
                          (scope.row.num = Number(value.replace(/[^\d]/g, '')))
                      "
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="num" label="赠送课时(节)" width="120">
                <template #default="scope">
                  <el-form-item
                    :prop="`tCoursePriceList.${scope.$index}.freeClassHours`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入赠送课时数',
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-input
                      v-model="scope.row.freeClassHours"
                      @change="changeData(scope.row, $event)"
                      @input="
                        (value) =>
                          (scope.row.freeClassHours = Number(
                            value.replace(/[^\d]/g, '')
                          ))
                      "
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="totalPrice" label="总价(元)" width="120">
                <template #default="scope">
                  <el-form-item
                    :prop="`tCoursePriceList.${scope.$index}.totalPrice`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入课时总价',
                        trigger: 'blur',
                      },
                      { validator: validatenum, trigger: 'blur' },
                    ]"
                  >
                    <el-input
                      v-model="scope.row.totalPrice"
                      @change="changeData(scope.row, $event)"
                      @input="
                        (value) =>
                          (scope.row.totalPrice = Number(
                            value.replace(/[^\d]/g, '')
                          ))
                      "
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="discountedPrice"
                label="折后价(元)"
                width="120"
              >
                <template #default="scope">
                  <el-form-item
                    :prop="`tCoursePriceList.${scope.$index}.discountedPrice`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入课时总折后价',
                        trigger: 'blur',
                      },
                      { validator: validatenum, trigger: 'blur' },
                    ]"
                  >
                    <el-input
                      v-model="scope.row.discountedPrice"
                      @change="changeData(scope.row, $event)"
                      @input="
                        (value) =>
                          (scope.row.discountedPrice = Number(
                            value.replace(/[^\d]/g, '')
                          ))
                      "
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="原单价(元/课时)" width="120">
                <template #default="scope">
                  <template v-if="scope.row.num > 0">{{
                    (scope.row.totalPrice / scope.row.num).toFixed(2)
                  }}</template>
                  <template v-else>自动计算</template>
                </template>
              </el-table-column>
              <el-table-column label="单价(元/课时)" width="120">
                <template #default="scope">
                  <template
                    v-if="scope.row.num + scope.row.freeClassHours > 0"
                    >{{
                      (
                        scope.row.discountedPrice /
                        (scope.row.num + scope.row.freeClassHours)
                      ).toFixed(2)
                    }}</template
                  >
                  <template v-else>自动计算</template>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click.prevent="deleteRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeW">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="submitForm"
          v-hasPermi="['registrar:course:add']"
          :disabled="openDisabled"
        >
          {{ loading ? "保存中..." : "保存" }}
        </el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Course">
import {
  saveCourseAPI,
  updateCourseAPI,
  getCourseListAPI,
  deleteCourseListAPI,
} from "@/api/registrar/course";
import JnColorPicker from "@/components/jnke/JnColorPicker";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const { sys_normal_disable, edu_teaching_mode } = proxy.useDict(
  "sys_normal_disable",
  "edu_teaching_mode"
);

function hasPermission(value) {
  const all_permission = "*:*:*";
  const permissions = useUserStore().permissions;
  if (value && value instanceof Array && value.length > 0) {
    const permissionFlag = value;
    return permissions.some((permission) => {
      return (
        all_permission === permission || permissionFlag.includes(permission)
      );
    });
  } else {
    throw new Error(`请设置操作权限标签值`);
  }
}
const courseList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openDisabled = ref(false);

const data = reactive({
  form: {
    id: undefined,
    name: undefined,
    lessonType: "1",
    state: "0",
    colour: "#e79138",
    payType: "1",
    tCoursePriceList: [],
    askLeavePunish: false,
    noShowPunish: false,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
    lessonType: null,
    state: null,
  },
});

const { queryParams, form } = toRefs(data);

const deleteRow = (index) => {
  form.value.tCoursePriceList.splice(index, 1);
};

const onAddItem = () => {
  form.value.tCoursePriceList.push({
    name: "",
    num: 0,
    freeClassHours: 0,
    totalPrice: 0,
    discountedPrice: 0,
    unitPrice: 0,
    originalUnitPrice: 0,
    payType: "1", // 先默认放入
  });
};

const changeData = (row, $event) => {
  if (row.num === 0) {
    row.originalUnitPrice = 0;
  } else {
    row.originalUnitPrice = (row.totalPrice / row.num).toFixed(2);
  }

  if (row.num + row.freeClassHours === 0) {
    row.unitPrice = 0;
  } else {
    row.unitPrice = (
      row.discountedPrice /
      (row.num + row.freeClassHours)
    ).toFixed(2);
  }
};

/** 查询授课方式列表 */
function getList() {
  loading.value = true;

  getCourseListAPI(proxy.addDateRange(queryParams.value, [])).then(
    (response) => {
      courseList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

/** 取消按钮 */
function closeW() {
  open.value = false;
  openDisabled.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    name: "",
    lessonType: "1",
    state: "0",
    colour: "#e79138",
    payType: "1",
    tCoursePriceList: [],
    askLeavePunish: false,
    noShowPunish: false,
  };
  proxy.resetForm("dictRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  //dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  open.value = true;
  openDisabled.value = false;
  title.value = "新增课程";
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function changeState(row) {
  let message = "";
  if (row.state == "1") {
    message = "确认停用此课程？";
  } else {
    message = "确认开课？";
  }
  proxy.$modal
    .confirm(message)
    .then(function () {
      updateCourseAPI({
        id: row.id,
        state: row.state,
      })
        .then((response) => {
          proxy.$modal.msgSuccess("操作成功");
          getList();
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      getList();
    });
}
/** 编辑按钮操作 */
function handleUpdate(row) {
  form.value = JSON.parse(JSON.stringify(row));
  open.value = true;
  title.value = "编辑课程";
  openDisabled.value = false;
}

function handleView(row) {
  form.value = JSON.parse(JSON.stringify(row));
  open.value = true;
  title.value = "查看课程";
  openDisabled.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dictRef"].validate((valid) => {
    if (valid) {
      if (form.value.tCoursePriceList.length === 0) {
        proxy.$modal.msgError("请补全报价单");
        return;
      }

      if (form.value.id != undefined) {
        updateCourseAPI(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("编辑成功");
            getList();
            closeW();
          })
          .catch(() => {
            loading.value = false;
          });
      } else {
        saveCourseAPI(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            getList();
            closeW();
          })
          .catch(() => {
            loading.value = false;
          });
      }
    } else {
      proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  if (row.state === "0") {
    proxy.$modal.msgError("请将课程停用后再做删除处理");
    return;
  }
  proxy.$modal
    .confirm('是否确认删除"' + row.name + '"？')
    .then(function () {
      return deleteCourseListAPI({ ids: [row.id] });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function handleDeleteList() {
  proxy.$modal
    .confirm("是否确认删除课程？")
    .then(function () {
      return deleteCourseListAPI({ ids: ids.value });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function validatenum(rule, value, callback) {
  if (value === 0) {
    callback(new Error("课时数不能为0"));
  } else {
    callback();
  }
}

getList();
</script>
<style scoped lang="scss">
.state-box {
  cursor: pointer;
}
.el-table__row .el-form-item {
  margin: 0;
}
</style>
